#!/bin/bash
clear
echo "Introduce los parametros conseguidos en el Área de Desarrolladores de Latch"
echo "                    https://latch.elevenpaths.com/www/"

echo "APLICATION ID ?"
read applicationId 

echo $applicationId >/home/Hackplayers/AID
echo "SECRETKEY ?"
read secretkey 
echo $secretkey >/home/Hackplayers/Sk
echo "codigo de emparejamiento?"
read empa
if [ "$2" == "debug" ]; then set -x; fi
#applicationId="EBP9PDFwH7ENf3pmEMeV"
#secretkey="8PY9nNisQdwCwaPB7ntCRKL74Vzdv768yvKkbPaW"
URL="/api/0.6/pair/$empa"
LATCH="latch.accounts"

if [ -z "$empa" ]; then
 echo -e "\nUsage: SITE LATCH-REG <pair-key>\n"
 exit 0
fi

if [ `grep "^$USER:" $LATCH | wc -l` -ne 0 ]; then
 echo -e "\nAlready registered\n"
 exit 0
fi

requestSignature+="GET\n"
date=`date -u '+%Y-%m-%d %H:%M:%S'`
requestSignature+="$date\n\n$URL"

signed=`echo -en "$requestSignature" | openssl dgst -sha1 -hmac "$secretkey" -binary|sed -e 's|.*= \(.*\)|\1|g'`
b64signed=`echo -n "$signed"|base64`
auth_header="Authorization:11PATHS $applicationId $b64signed"
date_header="X-11Paths-Date: $date"

JSON=`wget -q --no-check-certificate -O - --header "$auth_header" --header "$date_header" "https://latch.elevenpaths.com$URL"`
accountid=`echo "$JSON" | sed -e 's|.*accountId":"\(.*\)"}.*|\1|'| sed -e 's|\(.*\)".*|\1|g'`
if [ -z $accountid ]; then
 echo "Error."
else
 echo "$USER:$accountid" >> $LATCH
 echo -e "\nDone.\n"
fi
